package yxy.game.pm2.command.stairway;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.StairwayMessage;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.stairway.RankStairway;

import java.util.Collection;

/** 天梯争雄 天梯排行榜 */
@MessageType(proto = Command.StairwayRank, classtype = StairwayMessage.StairwayRankRequest.class)
public class CMD_StairwayRank extends Command<StairwayMessage.StairwayRankRequest> {

	@Override
	public void execute(MessageSource messageSource, StairwayMessage.StairwayRankRequest request) {
		String playerCode = messageSource.getTag();

		StairwayMessage.StairwayRankResponse.Builder response = StairwayMessage.StairwayRankResponse.newBuilder();
		try {
			PlayerBean playerBean = PlayerBean.get(playerCode);
			ServerBean serverBean = ServerBean.get(playerBean.getServerId());
			AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
			RankStairway rankStairway = new RankStairway(areaBean.getGroupId());

			PlayerHandle playerHandle = new PlayerHandle();
			Collection<RankEntry> top = rankStairway.top(rankStairway.topSize());
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int score = entry.getValue().intValue();

				StairwayMessage.StairwayRank.Builder builder = StairwayMessage.StairwayRank.newBuilder();

				builder.setRank(score);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
				response.addRank(builder);
			}
			{
				int score = 0;
				RankEntry entry = rankStairway.get(playerCode);
				if (entry != null) {
					score = entry.getValue().intValue();
				}

				StairwayMessage.StairwayRank.Builder builder = StairwayMessage.StairwayRank.newBuilder();
				builder.setRank(score);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(playerCode));
				response.setMy(builder);
			}
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, StairwayMessage.StairwayRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}